package com.kcyu.sfherp.service.impl;

import com.alibaba.fastjson.JSON;
import com.kcyu.sfherp.entity.LoginUser;
import com.kcyu.sfherp.entity.utilEntity.UserInfoDTO;
import com.kcyu.sfherp.mapper.ms.SysMapper;
import com.kcyu.sfherp.service.NotificationService;
import com.kcyu.sfherp.service.SysService;
import com.kcyu.sfherp.utils.JwtUtil;
import com.kcyu.sfherp.utils.RedisCache;
import com.kcyu.sfherp.utils.ResponseResult;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SysServiceImpl implements SysService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysMapper sysMapper;

    @Autowired
    private NotificationService notificationService;

    private final Long JWT_EXPIRETIME = (long) (7 * 24 * 60 * 60 * 1000);

    @Override
    public ResponseResult Login(UserInfoDTO userinfo, HttpServletResponse response) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userinfo.getUsername(), userinfo.getPassword());
        Authentication authenticate = null;

        try {
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            return new ResponseResult(300, "用户名或密码错误");
        }

        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid, JWT_EXPIRETIME);
        Map<String,Object> map = new HashMap<>();
        map.put("token",jwt);
        map.put("user_info", loginUser.getUser());
        //把完整的用户信息存入redis  userid作为key
        redisCache.setCacheObject("login:"+userid,loginUser);

        // 将cookie设置上去
        Cookie cookie = new Cookie("sfh-erp-token", jwt);
//        cookie.setDomain("kcyu.top");
        cookie.setPath("/");
        response.addCookie(cookie);

        // 通知我自己
        notificationService.sendNotification("登录通知", "用户" + loginUser.getUser().getName() + "登录了系统， 登录时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        return new ResponseResult(200,"登录成功", map);
    }

    @Override
    public ResponseResult Logout(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200, "退出成功");
    }

    @Override
    public ResponseResult getLog() {
        List<HashMap> browserHistory = redisCache.getCacheList("browser_history");
        List<HistoryBody> historyBodies = new ArrayList<>();
        for (HashMap historyBody : browserHistory) {
            HistoryBody historyBody1 = JSON.parseObject(JSON.toJSONString(historyBody), HistoryBody.class);
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            String date = format.format(historyBody1.getTime());
//            historyBody1.setTimeString(date);
            historyBodies.add(historyBody1);
        }
        Collections.reverse(historyBodies);
        System.out.println(historyBodies);
        return new ResponseResult(200, "获取成功", historyBodies);
    }

    @Override
    public ResponseResult clearLog() {
        redisCache.deleteObject("browser_history");
        return new ResponseResult(200, "删除成功");
    }

    @Data
    class HistoryBody {
        private Long time;
        private String value;
        private String operator;
        private String url;

//        private String timeString;
    }
}
